/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package videowarehouseapp;


import videostoreapp.Order.OrderInfo;

import java.io.Serializable;
import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.jms.ConnectionFactory;
import javax.jms.Destination;
import javax.jms.JMSException;
import javax.jms.Message;
import javax.jms.MessageConsumer;
import javax.jms.MessageListener;
import javax.jms.MessageProducer;
import javax.jms.ObjectMessage;
import javax.jms.Session;
import videowarehouseapp.Delivery.DeliveryInfo;
import videowarehouseapp.Stock.StockInfo;
import videowarehouseapp.dataobjects.DeliveryDO;
import videowarehouseapp.dataobjects.StockDO;

/**
 *
 * @author oiiv2253
 */
public class DeliveryMgr {

    private static DeliveryMgr mgr;

    private ConnectionFactory getCxn;
    private Destination getDest;
    private javax.jms.Connection conn;
    private MessageConsumer consumer;
    private Session sess;

    private ConnectionFactory sendCxn;
    private Destination sendDest;
   

    private DeliveryMgr() throws Exception {

        getCxn = Constants.getOrderConnectionFactory();
        getDest = Constants.getOrderQueue();

        sendCxn = Constants.getDeliveryConnectionFactory();
        sendDest = Constants.getDeliveryQueue();

    }

    public static DeliveryMgr getInstance () {

        if (mgr == null){
            try {
                mgr = new DeliveryMgr();
            } catch (Exception ex) {
                Logger.getLogger(DeliveryMgr.class.getName()).log(Level.SEVERE, null, ex);
            }
        }
      return mgr;

    }

    public void sendDeliveryMessage(DeliveryInfo di)
    {
        try{
            //create connection
            javax.jms.Connection conn = sendCxn.createConnection();
            Session session = conn.createSession(false, Session.AUTO_ACKNOWLEDGE);

            MessageProducer prod = session.createProducer(sendDest);
            ObjectMessage msg = session.createObjectMessage();

            msg.setObject((Serializable) di);
            msg.setJMSType("deliveryInfo");
            prod.send(msg);

        } catch (Exception ex) {
            Logger.getLogger(DeliveryMgr.class.getName()).log(Level.SEVERE, null, ex);
        }

    }

    public void sendStockMessage(List<StockInfo> warehouseStock, String warehouse)
    {
        try{
            //create connection
            javax.jms.Connection conn = sendCxn.createConnection();
            Session session = conn.createSession(false, Session.AUTO_ACKNOWLEDGE);

            MessageProducer prod = session.createProducer(sendDest);
            ObjectMessage msg = session.createObjectMessage();

            msg.setObject((Serializable) warehouseStock);
            msg.setJMSType("warehouse");
            msg.setStringProperty("warehouse", warehouse);
            prod.send(msg);

        } catch (Exception ex) {
            Logger.getLogger(DeliveryMgr.class.getName()).log(Level.SEVERE, null, ex);
        }

    }

    public void startQueueListener() throws Exception
    {
        //create connection
        conn = getCxn.createConnection();
        sess = conn.createSession(false, Session.AUTO_ACKNOWLEDGE);
        try{
            consumer = sess.createConsumer(getDest);
            consumer.setMessageListener(new MessageListener(){

                public void onMessage(Message message) {
                    System.out.println("it works!");
                    try {
                        DeliveryMgr.getInstance().treatMessage(message);
                    } catch (Exception ex) {
                        Logger.getLogger(DeliveryMgr.class.getName()).log(Level.SEVERE, null, ex);
                    }
                }
            });
            conn.start();
        } catch (JMSException e) {
            System.err.println("Exception occurred: " + e.toString());
        }
    }

    public void putBackMessage(OrderInfo oi)
    {
      try {
            //create connection
            javax.jms.Connection conn = getCxn.createConnection();
            Session session = conn.createSession(false, Session.AUTO_ACKNOWLEDGE);

            MessageProducer prod = session.createProducer(getDest);
            ObjectMessage msg = session.createObjectMessage();

            msg.setJMSType("order");
            msg.setObject(oi);
            prod.send(msg);

        } catch (Exception ex) {
            Logger.getLogger(DeliveryMgr.class.getName()).log(Level.SEVERE, null, ex);
        }finally{
            try {
                conn.close();
            } catch (JMSException ex) {
                Logger.getLogger(DeliveryMgr.class.getName()).log(Level.SEVERE, null, ex);
            }
        }

    }

    public void stopQueueListener() throws Exception{
        conn.close();
    }

    public void treatMessage(Message message) throws JMSException, Exception {
        System.out.println("Dealing with messages");
        String messageType=message.getJMSType();
        if (messageType.equals("order")) {
           ObjectMessage om = (ObjectMessage) message;
           OrderInfo oInfo = (OrderInfo) om.getObject();
           System.out.println("Processi   OrderInfo oInfo = (OrderInfo) om.getObject();ng message "+oInfo.id);
           System.out.println(oInfo.status);
           System.out.println(oInfo.orderDate);
           System.out.println(oInfo.store);
           Delivery d = new DeliveryDO();
           int delId = d.createDelivery(oInfo);
           System.out.println("Created delivery with id:" + delId);
           DeliveryInfo delInfo = d.getDeliveryById(delId);
           this.sendDeliveryMessage(delInfo);
       }else if (messageType.equals("status")){
           int id= message.getIntProperty("DeliveryId");
           Delivery d = new DeliveryDO();
           DeliveryInfo di=d.getDeliveryById(id);
           this.sendDeliveryMessage(di);
       }else if (messageType.equals("warehouse")){
           Stock s=new StockDO();
           String warehouse=message.getStringProperty("warehouse");
           List<StockInfo> warehouseStock=s.getItemByWarehouse(warehouse);
           this.sendStockMessage(warehouseStock, warehouse);
       }
    }


}


